package com.farsunset.cim.nio.filter;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.farsunset.cim.nio.constant.CIMConstant;
import com.farsunset.cim.nio.mutual.Message;
import com.farsunset.cim.nio.mutual.ReplyBody;
import com.kuaigou.cim.util.JSONHelper;

/**
 * 客户端消息解码
 * 
 * @author 3979434@qq.com
 *
 */
public class ClientMessageDecoder extends FrameDecoder {

	@Override
	protected Object decode(ChannelHandlerContext arg0, Channel channel,
			ChannelBuffer buffer) throws Exception {

		int length = buffer.readableBytes();
		/**
		 * CIMConstant.MESSAGE_SEPARATE 为消息界限 当一次收到多个消息时，以此分隔解析多个消息
		 */
		if (buffer.readable() && length > 0
				&& CIMConstant.MESSAGE_SEPARATE == buffer.getByte(length - 1)) {

			byte[] data = new byte[length - 1];
			buffer.readBytes(data);
			String message = new String(new String(data,
					CIMConstant.ENCODE_UTF8));

			System.out.println("ClientMessageDecoder:" + message);

			// 将末尾的消息分隔符读取掉
			buffer.readByte();

			Object msg = mappingMessageObject(message);

			data = null;
			message = null;
			return msg;
		}

		return null;
	}

	private Object mappingMessageObject(String message) throws Exception {
		if(message.indexOf("[KGCIM-SYSTEM]") != -1){
			return JSONHelper.jsonToEntity(message, Message.class);
		}else{
			return JSONHelper.jsonToEntity(message, ReplyBody.class);
		}		
	}

}
